<template>
  <el-pagination v-model:current-page="pageNum" v-model:page-size="pageSize" :page-sizes="pageSizes" :layout="layout" :total="total" @change="change" />
</template>

<script setup lang="ts">
import { onMounted, ref } from 'vue'

defineOptions({
  name: 'a-pagination'
})

interface Props {
  immediate?: boolean
  layout?: string
  total?: number
  pageSizes?: number[]
  defaultPageSize?: number
  defaultPageNum?: number
  change: (num: number, size: number) => void
}

const props = withDefaults(defineProps<Props>(), {
  immediate: true,
  layout: 'total, sizes, prev, pager, next, jumper',
  pageSizes: () => [10, 20, 50, 100],
  defaultPageSize: 10,
  defaultPageNum: 1,
  total: 0
})

const pageNum = ref(props.defaultPageNum)
const pageSize = ref(props.defaultPageSize)

function handleChange(reset?: boolean) {
  if (reset) {
    pageNum.value = props.defaultPageNum
    pageSize.value = props.defaultPageSize
  }

  props.change(pageNum.value, pageSize.value)
}

onMounted(() => {
  if (props.immediate) handleChange()
})

defineExpose({
  change: handleChange,
  pageNum: pageNum.value,
  pageSize: pageSize.value
})
</script>
